package org.xiaoyu.feign.core.annotation;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.xiaoyu.feign.core.FeignFactoryBean;
/**
 * feign服务注册
 * @author zhangsaizz
 *
 */
public class FeignConsumerRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware{

	private ResourceLoader resourceLoader;
	
	public static final String FEIGN_ZOOKEEPER_PATH = "/feignService";
	
	public static final String FEIGN_ZOOKEEPER = "feignZookeeper";
	
	private Environment environment;
	
	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;

	}

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AnnotationAttributes annoAttrs = AnnotationAttributes
				.fromMap(importingClassMetadata.getAnnotationAttributes(FeignConsumerScan.class.getName()));
		ClassPathFeignServiceScanner scanner = new ClassPathFeignServiceScanner(registry);
		if (resourceLoader != null) {
			scanner.setResourceLoader(resourceLoader);
		}
	    Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
	    if (!Annotation.class.equals(annotationClass)) {
	      scanner.setAnnotationClass(annotationClass);
	    }
	    Class<?> markerInterface = annoAttrs.getClass("markerInterface");
	    if (!Class.class.equals(markerInterface)) {
	      scanner.setMarkerInterface(markerInterface);
	    }
		scanner.setFeignFactoryBean(BeanUtils.instantiateClass(FeignFactoryBean.class));
		List<String> basePackages = new ArrayList<String>();
		for (String pkg : annoAttrs.getStringArray("value")) {
			if (StringUtils.hasText(pkg)) {
				basePackages.add(pkg);
			}
		}
		for (String pkg : annoAttrs.getStringArray("basePackages")) {
			if (StringUtils.hasText(pkg)) {
				basePackages.add(pkg);
			}
		}
		for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {
			basePackages.add(ClassUtils.getPackageName(clazz));
		}
		scanner.registerFilters();
		scanner.setEnvironment(this.environment);
		scanner.doScan(StringUtils.toStringArray(basePackages));

	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
		
	}

}
